<?php


namespace App\Models;

use App\Services\DeptService;
use App\Services\ImageService;
use App\Services\UserRoleService;
use Carbon\Carbon;

/**
 * 人员管理-模型
 * @author aaron
 * @since 2020/11/10
 * Class AdminModel
 * @package App\Models
 */
class UserModel extends BaseModel
{
    // 设置数据表
    protected $table = 'user';

    const SUPER_ADMIN_NAME = 'admin';

    protected $appends = [
        'avatar_url',
        'is_super_admin',
        'create_time_format',
        'update_time_format',
    ];

    protected $fillable = [
        'realname',
        'username',
        'password'
    ];

    public function getAvatarUrlAttribute()
    {
        return (new ImageService($this->avatar))->getUrl();
    }

    public function getCreateTimeFormatAttribute()
    {
        return Carbon::parse($this->create_time)->toDateTimeString();
    }

    public function getUpdateTimeFormatAttribute()
    {
        return Carbon::parse($this->update_time)->toDateTimeString();
    }

    public function getIsSuperAdminAttribute()
    {
        if ($this->username == self::SUPER_ADMIN_NAME) {
            return true;
        }
        return false;
    }

    /**
     * 获取数据信息
     * @param int $id 用户ID
     * @return array|string
     * @author aaron
     * @since 2020/11/10
     */
    public function getInfo($id)
    {
        $info = parent::getInfo($id); // TODO: Change the autogenerated stub
        if ($info) {
            $deptId = $info['dept_id'] ?? 0;

            // 头像
            if ($info['avatar']) {
                $info['avatar'] = (new ImageService($info['avatar']))->getUrl('resources/imgs/placeholder-avatar.png');
            }

            // 性别
            if ($info['gender']) {
                $info['gender_name'] = config('admin.gender_list')[$info['gender']];
            }

            // 出生日期
            if ($info['birthday']) {
                $info['birthday'] = datetime($info['birthday']);
            }

            // 岗位
            if ($info['position_id']) {
                $positionModel = new PositionModel();
                $positionInfo = $positionModel->getInfo($info['position_id']);
                $info['position_name'] = $positionInfo['name'];
            }

            // 职级
            if ($info['level_id']) {
                $levelMod = new LevelModel();
                $levelInfo = $levelMod->getInfo($info['level_id']);
                $info['level_name'] = $levelInfo['name'];
            }

            // 部门
            if ($info['dept_id']) {
                $deptModel = new DeptModel();
                $deptInfo = $deptModel->getInfo($info['dept_id']);
                $info['dept_name'] = $deptInfo ? $deptInfo['name'] : "";
                $info['dept_id'] = $deptInfo['id'] ?? 0;
            }

            // 城市
            $city = [];
            $city[] = !empty($info['province_code']) ? strval($info['province_code']) : "";
            $city[] = !empty($info['city_code']) ? strval($info['city_code']) : "";
            $city[] = !empty($info['district_code']) ? strval($info['district_code']) : "";
            $info['city'] = $city;

            $provinceCode = $info['province_code'] ?? '';
            $cityCode = $info['city_code'] ?? '';
            $districtCode = $info['district_code'] ?? '';

            $cities = CityModel::query()
                ->whereIn('citycode', [$provinceCode, $cityCode, $districtCode])
                ->get()
                ->keyBy('citycode')
                ->toArray();
            $info['province_name'] = $cities[$provinceCode]['name'] ?? '';
            $info['city_name'] = $cities[$cityCode]['name'] ?? '';
            $info['county_name'] = $cities[$districtCode]['name'] ?? '';

            // 获取用户角色列表
            $userRoleService = new UserRoleService();
            $roleList = $userRoleService->getUserRoleList($id);
            $info['roles'] = $roleList;

            // 区域经理信息
            $managers = (new DeptService())->getManagersByDeptId($deptId);
            $manager = $managers[0] ?? [];
            $info['managers'] = $managers;
            $info['manager'] = $manager;

            // 是否是区域经理
            $info['is_manager'] = $id == 1 || (new DeptService())->isManagerEngineer($id);
        }
        return $info;
    }

    public function scopeByRealname($query, $realname)
    {
        return $query->where('realname', $realname);
    }

    public function scopeByUsername($query, $username)
    {
        return $query->where('username', $username);
    }

    public function roles()
    {
        return $this->hasMany(UserRoleModel::class, 'user_id');
    }

    // 是否是售后总监
    public function isServiceManager()
    {
        $count = UserRoleModel::query()
            ->join('role as r', 'r.id', '=', 'user_role.role_id')
            ->where('r.name', '=', '售后总监')
            ->where('user_role.user_id', $this->id)
            ->count();
        return (bool)$count;
    }
}
